package org.llp.org.controller;

import org.llp.basic.utils.AjaxResult;
import org.llp.basic.utils.PageList;
import org.llp.org.domain.Department;
import org.llp.org.query.DepartmentQuery;
import org.llp.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    //新增删除（保存）
    @PutMapping
    public AjaxResult save(@RequestBody Department department){
        try {
            if(department.getId() != null){
                departmentService.update(department);
            }else{
                departmentService.add(department);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败"+e.getMessage());
        }
        return new AjaxResult().me();
    }

    //删除操作
    @DeleteMapping("/{id}")
    public AjaxResult removeById(@PathVariable("id")Long id){
        try {
            departmentService.removeById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败"+e.getMessage());
        }
        return new AjaxResult().me();
    }
    //查询操作
    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable("id")Long id){
        try {
            Department department = departmentService.getById(id);
            return AjaxResult.me().setResult(department);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("查询失败"+e.getMessage());
        }
    }
    //查询所有
    @GetMapping
    public AjaxResult getAll(){
        try {
            List<Department> departments = departmentService.getAll();
            return AjaxResult.me().setResult(departments);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("查询失败"+e.getMessage());
        }
    }
    //分页查询
    @PostMapping
    public AjaxResult pageList(@RequestBody DepartmentQuery query){
        try {
            PageList<Department> pageList = departmentService.pageList(query);
            return AjaxResult.me().setResult(pageList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("查询失败"+e.getMessage());
        }
    }

    @GetMapping("/tree")
    public AjaxResult getDepartmentTree(){
        try {
            List<Department> departments = departmentService.getDepartmentTree();
            return AjaxResult.me().setResult(departments);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("查询失败"+e.getMessage());
        }
    }





}
